package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.config.DfsProperties;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.lewin.movie.entity.MovieScene;
import la.iok.hzsvn.lewin.movie.entity.MovieSceneFile;
import la.iok.hzsvn.lewin.movie.entity.MovieSceneInstance;
import la.iok.hzsvn.lewin.movie.mapper.MovieSceneFileMapper;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.annotations.Nullable;
import la.iok.hzsvn.share.dfs.model.DfsDescriptor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class MovieSceneFileServiceImpl extends MovieFileServiceImpl<MovieSceneFile, MovieSceneFileMapper> implements MovieSceneFileService {
    public MovieSceneFileServiceImpl(MovieSceneFileMapper mapper, WebDfsService webDfsService, DfsProperties dfsProperties) {
        super(mapper,webDfsService, dfsProperties);
    }

    @Override
    public void downloadFile(@NotNull HttpServletResponse response, @Nullable Long id, @NotNull String sceneName) {
        MovieSceneFile sceneFile = select(id);
        ErrorCode.SCENE_FILE_NOT_EXIST.assertNotNull(sceneFile,sceneName);
        DfsDescriptor descriptor = webDfsService.dfsFile(sceneFile.getPath());
        ErrorCode.SCENE_FILE_NOT_EXIST.assertTrue(webDfsService.exist(descriptor),sceneName);
        webDfsService.downloadFile(response,descriptor,sceneFile.getFileName());
    }

    @Override
    protected void validateReference(@NotNull MovieSceneFile file) {
        MovieSceneInstance item = executeSelect(MovieSceneInstance.class,"select * from "
                + MovieSceneInstance.class.getSimpleName() + " where fileDeleted=0 and (fileId=" + file.getId() + " or encodedFileId=" + file.getId() + ") limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item,file.getPath(),MovieSceneInstance.class.getSimpleName());

        MovieScene item2 = executeSelect(MovieScene.class,"select * from "
                + MovieScene.class.getSimpleName() + " where fileId=" + file.getId() + " limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item2,file.getPath(),MovieScene.class.getSimpleName());

    }
}
